<template>
  <el-card class="blog-edit-card">
    <div slot="header">
      <h2>编辑博客</h2>
    </div>
    <el-form ref="blogForm" :model="blogForm" :rules="rules" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="blogForm.title"
          placeholder="请输入博客标题"
          size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          type="textarea"
          v-model="blogForm.content"
          placeholder="请输入博客内容"
          :rows="15"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" icon="el-icon-check"
          >保存</el-button
        >
        <el-button @click="handleCancel" icon="el-icon-close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        blogForm: {
          title: "",
          content: "",
        },
        blogId: null,
        rules: {
          title: [
            { required: true, message: "请输入博客标题", trigger: "blur" },
            {
              min: 3,
              max: 100,
              message: "标题长度在 3 到 100 个字符",
              trigger: "blur",
            },
          ],
          content: [
            { required: true, message: "请输入博客内容", trigger: "blur" },
            { min: 10, message: "内容不能少于 10 个字符", trigger: "blur" },
          ],
        },
      };
    },
    created() {
      this.blogId = this.$route.params.id;
      this.loadBlogData();
    },
    methods: {
      async loadBlogData() {
        try {
          let blog = await this.$axios.get(`/blog/${this.blogId}`);
          blog = blog.data;
          // 验证权限：只有作者可以编辑
          const user = this.$store.getters.user;
          // const user = JSON.parse(localStorage.getItem("user") || "{}");
          if (user.userId !== blog?.user_id) {
            this.$message.error("没有权限编辑此博客");
            this.$router.push(`/blog/${this.blogId}`);
            return;
          }

          this.blogForm = {
            title: blog.title,
            content: blog.content,
          };
        } catch (error) {
          this.$message.error("加载博客数据失败");
          console.error(error);
        }
      },
      async handleSubmit() {
        this.$refs.blogForm.validate(async (valid) => {
          if (valid) {
            try {
              await this.$axios.put(`/blog/${this.blogId}`, this.blogForm);
              this.$message.success("博客更新成功");
              this.$router.push(`/blog/${this.blogId}`);
            } catch (error) {
              this.$message.error("更新失败");
              console.error(error);
            }
          } else {
            return false;
          }
        });
      },
      handleCancel() {
        this.$router.go(-1);
      },
    },
  };
</script>

<style scoped>
  .blog-edit-card {
    max-width: 1000px;
    margin: 20px auto;
  }
</style>
